Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement app typing (strict) #513

Closed
wants to merge 2 commits into from
Closed

Conversation

Dreamsorcerer
Copy link
Member

@Dreamsorcerer Dreamsorcerer commented Nov 21, 2021

Demonstration of how Application typing can work with a library. This is a stricter approach, where users (who use strict typing) would need to inherit from aiohttp_jinja2.AppState.

For example, a user application might look like this:

class AppState(aiohttp_jinja2.AppState):
    foo: str

MyRequest = web.Request[AppState]

app: web.Application[AppState] = web.Application()
app.state["foo"] = "bar"
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('/path/to/templates/folder'))

@aiohttp_jinja2.template('tmpl.jinja2')
async def handler(request: MyRequest) -> Dict[str ,str]:
    return {''foo': request.app.state['foo']}

Breaking change

For typing to work correctly, we need to have hardcoded keys. This means deprecating the customisable app_key argument.
I think this only exists to help with clashes in key names. I suspect almost nobody actually uses this and am fine removing it in a future release. I've also prefixed the private aiohttp-jinja2 names with _ to further reduce the likelihood that it will conflict with someone's object.

Plus, with better static typing, it's much easier for someone to tell if they used the same name. For example, this will give an error in mypy:

class AppState(aiohttp_jinja2.AppState):
    foo: str
    _aiohttp_jinja2_environment: Dict[str, str]

@Dreamsorcerer Dreamsorcerer changed the title Implement app typing Implement app typing (strict) Nov 22, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant